const logger = require('./builder.log');
const shell = require('./builder.shell');
const componentBuilder = require('./builder.components');

const PageBuilder = function(){

    let _build = function *(distPath, appConfig, appPages) {
        logger.notice("Begin Builder Pages:" );
        for(var i = 0; i < appPages.length; i++){
            var p = appPages[i];
            try{
                let pageName = `page${p.id}`;
                logger.info(`Build Page: ${pageName}`);

                let contents = yield componentBuilder.build(p);
                let templatePath = `src/pages/${p.templateName}`;
                //生成 xml
                let templateXmlContent = yield shell.exec(`cat ${templatePath}/page.xml`);
                let xmlContent = templateXmlContent.replace('<!--{ComponentXml}-->', contents.xmlContent);
                    //.replace(/'/g,`"'"`);
                    console.log("xml:" + xmlContent);
                yield shell.exec(`echo '${xmlContent}' > ${distPath}/pages/${pageName}.wxml`);

                //生成 js
                let templateJsContent = yield shell.exec(`cat ${templatePath}/page.js`);
                let jsContent = templateJsContent.replace('/*{ComponentJs}*/', contents.jsContent)
                    .replace('/*{ComponentLaunchJs}*/', contents.launchContent)
                    .replace(/'/g,`"'"`);
                yield shell.exec(`echo '${jsContent}' > ${distPath}/pages/${pageName}.js`);

                //生成 json
                let templateJsonContent = yield shell.exec(`cat ${templatePath}/page.json`);
                if (templateJsonContent !== false){
                  let jsonContent = templateJsonContent
                      .replace(/'/g,`"'"`);
                  yield shell.exec(`echo '${jsonContent}' > ${distPath}/pages/${pageName}.json`);
                }
                //生成 css
                let templateCssContent = yield shell.exec(`cat ${templatePath}/page.css`);
                let cssContent = templateCssContent.replace('/*{ComponentCss}*/', contents.cssContent)
                    .replace(/'/g,`"'"`);
                yield shell.exec(`echo '${cssContent}' > ${distPath}/pages/${pageName}.wxss`);
            }catch(e){
                logger.error(e);
            }
        }


        return true;
    };

    return {
        build: _build
    }
}();

module.exports = PageBuilder;
